<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/5/7
 * Time: 20:19
 * Desc: 微信刷卡支付
 */
namespace app\cash\controller;
use think\Controller;
use think\Db;
use Wechat\WechatPay;
use app\comm\service\WeixinpayService;


class Wxguadan extends Controller{
    /**
     * @Author  lingyun
     * @Desc    支付页面
     * @return mixed
     */
    public function pay(){
        $order_id = input('param.order_id');
        $auth_code = input('param.auth_code');
        if(empty($auth_code)){
            $this->error('订单创建失败，请重新创建');
//            return ['code'=>0,'订单创建失败，请重新创建'];
        }

        if(empty($order_id)){
            $this->error('订单创建失败，请重新创建');
//            return ['code'=>0,'msg'=>'订单创建失败，请重新创建'];
        }
        $order = db('order')->where('id',$order_id)->find();
        $order['final_amount'] = $order['final_amount']*100;
        if(empty($order)){
            $this->error('订单创建失败，请重新创建');
//            return ['code'=>0,'msg'=>'订单创建失败，请重新创建'];
        }
        if($order['pay_status'] > 0){          //已经支付
            $this->success(2,'',$order['receipt']);
//            return ['code'=>1,'msg'=>'支付成功'];
        }

        $wxpay = new WechatPay();
        $pay = & load_wechat('Pay');

        $result = $pay->createMicroPay($auth_code, $order['order_sn'], $order['final_amount'], '微信刷卡支付', $goods_tag = null);

        //确认支付是否成功
        $service = new WeixinpayService();		//实例化微信支付类
        $queryTimes = 10;
        $order_state = array();
        $error_msg = '';
        $code = 1;
        while($queryTimes > 0)
        {
            $succResult = 0;
            $queryResult = $service->get_shuaka_order($order['order_sn']);
            //如果需要等待1s后继续
            if($queryResult['succCode'] == 2){
                sleep(2);
                $queryTimes--;          //2018-05-29修改防止跑死
                continue;
            } else if($queryResult['succCode'] == 1){//查询成功
                $order_state = $queryResult['result'];
                break;
//                return $queryResult['result'];
            } else {//订单交易失败
                $error_msg = $queryResult['result'];
                $code = 0;
                break;
            }
        }

        if($code == 1){
            $order = db('order')->where('order_sn',$order_state['out_trade_no'])->find();
            $store = db('store')->where('id',$order['store_id'])->find();
            if($order['pay_status'] > 0){
                $this->success(2,'',$order['receipt']);
            }else{      //更新订单状态
                $receipt = $order['receipt'];

                $pay_type_two = $order['pay_type_two'];
                $pay_type = $order['pay_type'];
                if($pay_type_two == 0){
                    $use_yue = '';
                    $pty = $order['final_amount']-$pay_type_two;
                }else{
                    $use_yue = '|会员卡：('.$pay_type_two.')';
                    $pty = $order['final_amount']-$pay_type_two;
                }

                if($pay_type == 1){
                    $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：支付宝（'.$pty.'）'.$use_yue.'</td></tr>';
                }else if($pay_type == 2){
                    $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：微信（'.$pty.'）'.$use_yue.'</td></tr>';
                }else if($pay_type == 3){
                    $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：会员卡（'.$pty.'）'.$use_yue.'</td></tr>';
                }else if($pay_type == 4){
                    $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：现金（'.$pty.'）'.$use_yue.'</td></tr>';
                }else if($pay_type == 5){
                    $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：银行卡（'.$pty.'）'.$use_yue.'</td></tr>';
                }else if($pay_type == 6){
                    $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：美团（'.$pty.'）'.$use_yue.'</td></tr>';
                }else if($pay_type == 7){
                    $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：饿了么（'.$pty.'）'.$use_yue.'</td></tr>';
                }


                if(!empty($order['uid'])){            //显示会员信息
                    $member = db('user')->where('uid',$order['uid'])->find();
                    if($order['pay_type_two'] > 0){         //余额付款
                        $user_money = $member['user_money'] - $order['pay_type_two'];
                    }else{
                        $user_money = $member['user_money'];
                    }

                    $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">姓名：' . $member["realname"] . '     手机：￥' . $member["mobile"] . '</td></tr>';
                    $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">会员卡：' . $member["pay_code"] . '     余额：￥' . $user_money . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
                }
                $receipt .= '<tr><td colspan="4" style="text-align: left;font-size: smaller;">' . $store["address"] . '</td></tr>';
                $receipt .= '<tr><td colspan="4" style="text-align: left">' . date('Y-m-d H:i:s') . '</td></tr>';
                $receipt .= '<tr><td colspan="4" style="text-align: left">' . '欢迎您再次光临' . '</td></tr>';

                db('order')->where('order_sn',$order_state['out_trade_no'])->update(['pay_status'=>1,'pay_time'=>time(),'pay_code'=>$order_state['transaction_id'],'order_status'=>4,'pay_type'=>1,'receipt'=>$receipt]);
                if($order['coupon_id'] != ''){
                    db('user_ycard')->where(['coupon_id'=>$order['coupon_id'],'uid'=>$order['uid']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
                }

                db('order_details')->where('order_id',$order['id'])->update(['status'=>4]);
                $order_action_arr = [
                    'uid'=>$order['uid'],
                    'order_id'=>$order['id'],
                    'action_user'=>0,
                    'order_status'=>4,
                    'pay_status'=>1,
                    'status_desc'=>'订单已完成',
                    'storeid'=>$order['store_id'],
                    'addtime'=>time()
                ];
                db('order_action')->insert($order_action_arr);          //插入订单动作信息

                if($order['coupon_id'] != ''){
                    db('user_ycard')->where(['coupon_id'=>$order['coupon_id'],'uid'=>$order['uid']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
                }

                $pay_log_arr = [
                    'order_id'=>$order['id'],
                    'order_sn'=>$order['order_sn'],
                    'order_type'=>2,
                    'uid'=>$order['uid'],
                    'pay_type'=>1,
                    'pay_sign'=>1,
                    'store_id'=>$order['store_id'],
                    'amount'=>$order['final_amount']-$order['pay_type_two'],
                    'remark'=>'线下购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                    'addtime'=>time()
                ];
                db('pay_log')->insert($pay_log_arr);            //新增支付记录

                if(!empty($order['pay_type_two'])){
                    $pay_log_arr = [
                        'order_id'=>$order['id'],
                        'order_sn'=>$order['order_sn'],
                        'order_type'=>2,
                        'uid'=>$order['uid'],
                        'pay_type'=>3,
                        'pay_sign'=>1,
                        'store_id'=>$order['store_id'],
                        'amount'=>$order['pay_type_two'],
                        'remark'=>'线下购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                        'addtime'=>time()
                    ];
                    db('pay_log')->insert($pay_log_arr);            //新增支付记录
                }

                if(!empty($order['uid'])){
                    //变更积分
                    shouyintai_point($order['uid'],$order['final_amount'],$order['store_id'],$order['id'],$money=0,$order['order_sn'],1);
                }
                $pay_type_two = (float)$order['pay_type_two'];
                $this->update_store_money($order['uid'],$store['id'],$order_id,$order['order_sn'],$order['pay_type_two'],$order,$store);

                $casher = db('system_user')->where('id',$order['cashier'])->find();

                $order_details = db('order_details')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where('a.order_id',$order['id'])->field('a.id,a.goods_id,a.store_goods_stock_id,a.spec_detail,b.name,a.goods_num,a.final_amount,spec_price')->select();

                foreach($order_details as $k => $v){
                    $stock = db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->find();
                    $cur_stock = $stock['stock'] - $v['goods_num'];
                    //更新门店库存
                    db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->update(['stock'=>$cur_stock]);
                    $arr = [
                        'goods_id'=>$v['goods_id'],
                        'goods_spec_id'=>$stock['goods_spec_id'],
                        'title'=>$v['spec_detail'],
                        'order_id'=>$order['id'],
                        'store_id'=>$order['store_id'],
                        'types'=>2,
                        'ruku_num'=>0,
                        'tuihuo_num'=>0,
                        'chuku_num'=>$v['goods_num'],
                        'sunhao_num'=>0,
                        'remark'=>$order['order_sn'],
                        'cur_stock'=>$cur_stock,
                        'addtime'=>time(),
                        'order_sn'=>$order['order_sn']
                    ];
                    db('store_goods_log')->insert($arr);
                }
                $this->success(2,'',$order['receipt']);
            }
        }else{
            $this->error($error_msg,'');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    更新门店余额
     */
    private function update_store_money($uid=0,$store_id,$order_id,$sn,$pay_type_two=0,$order,$store){
        if(!empty($uid)){
            $member = db('user')->where('uid',$uid)->find();
            if(!empty($pay_type_two)){
                $data_wallet_arr = [
                    'uid' => $uid,
                    'admin_id' => 0,
                    'store_id' => $store_id,
                    'order_id' => $order_id,
                    'order_sn' => $sn,
                    'pay_time' => time(),
                    'pay_status' => 1,
                    'pay_type' => 3,
                    'amount' => $pay_type_two,
                    'cur_amount' => $member['user_money'] - $pay_type_two,
                    'sign' => 2,
                    'chargetype' => 1,
                    'charge_cn' => '支付订单',
                    'addtime' => time()
                ];
                //记录余额记录
                db('user_wallet_log')->data($data_wallet_arr)->insert();       //记录余额记录
                db('user')->where('uid', $uid)->setDec('user_money', $pay_type_two);
            }
        }
        $log_money = $order['final_amount'] - $pay_type_two;
        $store_credit_log = [
            'store_id' => $store_id,
            'order_id' => $order_id,
            'type' => 1,
            'credit' => $log_money,
            'cur_credit' => $store['total_amount'] + $log_money,
            'remark' => '销售商品收入',
            'addtime' => time(),
            'order_type' => 1,
            'order_sn' => $sn,
            'pay_type' => 1
        ];
        db('store_credit_log')->insert($store_credit_log);
        $store_credit_arr['total_amount'] = $store['total_amount'] + $log_money;
        $store_credit_arr['al_money'] = $store['al_money'] + $log_money;
        db('store')->where('id', $store_id)->update($store_credit_arr);

        if(!empty($pay_type_two)){
            $store_credit_log1 = [
                'store_id' => $store_id,
                'order_id' => $order_id,
                'type' => 1,
                'credit' => $pay_type_two,
                'cur_credit' => $store['total_amount'] + $log_money + $pay_type_two,
                'remark' => '销售商品收入',
                'addtime' => time(),
                'order_type' => 1,
                'order_sn' => $sn,
                'pay_type' => 3
            ];
            db('store_credit_log')->insert($store_credit_log1);
            $store_credit_arr1['total_amount'] = $store['total_amount'] + $log_money + $pay_type_two;
            $store_credit_arr1['credit'] = $store['credit'] + $pay_type_two;
            $store_credit_arr1['user_money'] = $store['user_money'] + $pay_type_two;
            db('store')->where('id', $store_id)->update($store_credit_arr1);
        }
    }

}